package cn.zcy.springboot_springsecurity02.config;

import cn.zcy.springboot_springsecurity02.handler.MyAuthenticationFailerHandler;
import cn.zcy.springboot_springsecurity02.handler.MyAuthenticationSuccessHandler;
import cn.zcy.springboot_springsecurity02.service.impl.MyUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    MyUserDetailServiceImpl myUserDetailService;

    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("fox").password(passwordEncoder().encode("111"))
                .authorities("ROLE_add").roles("admin")
        ;
    }

    /**
     * 配置之后，授权也需要显示指定，否则授权不生效
     *
     * @param http
     * @throws Exception
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //认证
        http.formLogin() //表单登录
                .loginPage("/login.html")
                .loginProcessingUrl("/user/login")//登录访问的路径
//                .defaultSuccessUrl("/admin/user/index") //认证成功的处理
                .successHandler(new MyAuthenticationSuccessHandler("/admin/hello")); //自定义认证成功的处理
//                .failureHandler(new MyAuthenticationFailerHandler("/error.html"));//自定义认证失败的处理，需要将页面放行
        //session失效跳转
        http.sessionManagement()
//                .invalidSessionUrl("/session/invalid") //失效
                .maximumSessions(1)//session的并发控制
                .maxSessionsPreventsLogin(true);//
        //授权
        http.authorizeRequests()
                .antMatchers("/login.html", "/user/login").permitAll()
                .antMatchers("/error.html", "/session/invalid").permitAll()
                .antMatchers("/admin/hello").hasAuthority("add") //匹配这个路径有这个权限才能访问
                .antMatchers("/admin/index").hasAuthority("user2") //匹配这个路径有这个权限才能访问
                .anyRequest().authenticated();
        http.csrf().disable(); //csrf 保护关闭
    }
}
